<?php
/*
	This file is part of PGallery; a FrogCMS plugin.

	PGallery is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	PGallery is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with PGallery.  If not, see <http://www.gnu.org/licenses/>.
*/


/**
 * PGallery plugin - image/photo gallery plugin that uses ImageMagick as its backend
 *
 * @package frog
 * @subpackage plugin.pgallery
 *
 * @author Craig Rodway <craig.rodway@gmail.com>
 * @version 1.0
 * @since Frog version 0.9.5
 * @license http://www.gnu.org/licenses/agpl.html AGPL License
 * @copyright Craig Rodway, 2009
 */

 
class PGallery
{
	
	var $image;
	var $cat;
    
	
	public function __construct(&$page, $params)
    {
		
		$this->page =& $page;
        $this->params = $params;
		
		if(empty($params)){
			
			// Root of everything..
			$this->contents(NULL);
			
			
		} else {
			
			// Get last param item
			$last = end($params);
			
			// Check if it contains : (for image)
			if(preg_match('/:/', $last)){
				// Show image page
				$parts = explode(':', $last);
				$this->image = $parts[0];
				$this->showimage($this->image);
			} else {
				// Show cat contents page
				$parts = explode('.', $last);
				$this->cat = $parts[0];
				$this->contents($this->cat);
			}
			
		} 

        
    }
	
	
	
	
	/*
	# # Logic for loading URLs # #
	
	1. Get possible categories and their sub-cats, and put into array
		[] = cat1
		[] = cat1/cat4
		[] = cat1/cat4/cat5
		[] = cat2/cat6
		[] = cat3
	
	2. get actual URL params into format of param1/param2
	
	3. Find out if we are looking at displaying a list of items in a cat, or a single item page
	
		to get the entry we're looking for: explode() on params, then get last item.
		if(in_array($params, $cat_urls)){
			// category
		} else {
			// item
		}
		
		
		request url: cat1/cat4/cat5/item6: not in array, so show image on its own page (last param)
		request url: cat2/cat5:	in array, so show cats+images in that cat
	*/
	
	
	
	
	/**
	 * Show the contents of a category or at root level
	 *
	 * @param	int		Category ID		ID of category to show (or can be NULL for root)
	 */
	private function contents($category_id){
		
		global $__FROG_CONN__;
		
		// If no category ID, then show all root categories
		if($category_id == NULL){
			
			// Get the categories at the base level
			$sql = 'SELECT c.id, c.name, c.slug, c.description, filename, "cat" AS type 
					FROM pgallery_categories c 
					WHERE (c.parent_id IS NULL OR c.parent_id = 0) AND c.visible = 1';
			
		} else {
			
			// Get cats+images from a sub-category
			$sql = '(SELECT
						id, name, slug, description, filename, "image" AS type
						FROM pgallery_images i
						WHERE i.category_id = %1$d
						ORDER BY name ASC)
					UNION
					(SELECT
						id, name, slug, description, filename, "cat" AS type
						FROM pgallery_categories c
						WHERE parent_id = %1$d AND visible = 1
						ORDER BY name ASC)
					ORDER BY type ASC, name ASC';
			
			$sql = sprintf($sql, $category_id);
			
		}
		
		// Do database query
		$db = $__FROG_CONN__->prepare($sql);
		$query = $db->execute();
		$items = $db->fetchAll(5);
		
		// Get info on container category
		$category = Category::findByIdFrom('Category', $category_id);
		
		// Get parent category
		$parent = NULL;
		if(is_object($category)){
			if($category->parent_id > 0){
				// Get the actual proper parent category
				$parent = Category::findByIdFrom('Category', $category->parent_id);
				if(is_object($parent)){
					// Some string magic to strip the last "folder" off the current URL
					$thisurl = preg_replace('/\/$/', '', $this->gurl(''));
					$prevurl = substr($thisurl, 0, strrpos($thisurl, '/'));
					$parent->url = $prevurl;
				}
			} else {
				// Make a new object to replicate the 'root' level
				$parent = new Category;
				$parent->url = get_url($this->page->url);
				$parent->name = "Gallery";
			}
		}
		
		// Set page title if present to include the category title
		$title = (is_object($category)) ? 'Gallery - ' . $category->name : 'Gallery';
		
		// Get plugin settings
		$settings = Plugin::getAllSettings('pgallery');
		$urlpath = preg_replace('/\\\/', '/', $settings['upload_path']) . '/';
		
		$types['cat'] = 'Category';
		$types['image'] = 'Image';
		
		// Set the URL to load for each item
		foreach($items as &$item){
			
			// Set the URL that it should link to
			$item->url = $this->gurl($item->id . ($item->type == 'image' ? ':' : '.') . $item->slug);
			
			// Set image paths
			foreach(array('small', 'medium', 'large') as $size){
				$paths[$size] = $urlpath . str_replace('#', $size, $item->filename);
			}
			$item->paths = $paths;
			unset($paths);
			
		}
		
		// Load the gallery page
		$body = new View('../../plugins/pgallery/views/front/contents', array(
			'items' => $items,
			'error' => $db->errorInfo(),
			'category' => $category,
			'types' => $types,
			'settings' => $settings,
			'parent' => $parent,
		));
		
		// Finally output the page to the screen
		$this->out($body, 'body', $title);
	}
	
	
	
	
	/**
	 * Show the page that includes a bigger version of the image
	 *
	 * @param	int		ID		ID of the image to show
	 */
	private function showimage($id){
		
		// Retrieve image from DB
		$image = Image::findByIdFrom('Image', $id);
		

		
		// Get plugin settings
		$settings = Plugin::getAllSettings('pgallery');
		$urlpath = preg_replace('/\\\/', '/', $settings['upload_path']) . '/';
		
		// Check we got an image
		if(is_object($image)){
			
			// Set image paths
			foreach(array('small', 'medium', 'large') as $size){
				$paths[$size] = $urlpath . str_replace('#', $size, $image->filename);
			}
			$image->paths = $paths;
			
			// Get parent category of this image
			$parent = Category::findByIdFrom('Category', $image->category_id);
			if(is_object($parent)){
				$parent->url = $this->gurl($parent->id . '.' . $parent->slug);
			}
			
		}
		
		// Load the image view for the page
		$body = new View('../../plugins/pgallery/views/front/image', array(
			'image' => $image,
			'parent' => $parent,
		));
		
		// Get title
		$title = (is_object($image)) ? 'Gallery - ' . $image->name : 'Gallery';
		
		// Show page
		$this->out($body, 'body', $title);
		
	}
	
	
	
	
	/**
	 * Return the full URL to a front-end page using PGallery
	 *
	 * @param	string	str		URL string (example: cat1/item2)
	 * @return	string			Like: http://example.com/page/cat1/item2
	 */
	private function gurl($str){
		$params = '/'.implode('/', $this->params).'/';
		$params = preg_replace('/[\/]+/', '/', $params);
		return get_url($this->page->url.$params.$str);
	}
	
	
	
	
	/**
	 * Content replacement on the page parts
	 *
	 * @param	string	html	String of HTML to search and replace for {gallery}..
	 * @param	string	part	Page part to update
	 * @param	string	title	Title of the page to set
	 */
	function out($html, $part = 'body', $title = NULL){
		
		$this->page->part->$part->content_html = preg_replace('/{gallery}/', $html, $this->page->part->$part->content_html);
		
		if($title != NULL){
			$this->page->title = $title;
		}
		
	}

	
	
	
	private function _slug_to_id($type, $slug){
		
		global $__FROG_CONN__;
		
		switch($type){
			case 'cat':
				$sql = "SELECT id FROM pgallery_categories WHERE slug = ? LIMIT 1";
				break;
				
			case 'image':
				$sql = "SELECT id FROM pgallery_images WHERE slug = ? LIMIT 1";
				break;
		}
		
		$db = $__FROG_CONN__->prepare($sql);
		$db->execute(array($slug));
		
		$row = $db->fetchObject();
		return $row->id;
		
	}
	
    
	
	
}


/* End of file: pgallery/pgallery.php */